import com.aliyun.auth.credentials.Credential
import com.aliyun.auth.credentials.provider.StaticCredentialProvider
import com.aliyun.sdk.service.alidns20150109.AsyncClient
import com.aliyun.sdk.service.alidns20150109.models.DescribeSubDomainRecordsRequest
import com.aliyun.sdk.service.alidns20150109.models.DescribeSubDomainRecordsResponseBody
import com.aliyun.sdk.service.alidns20150109.models.UpdateDomainRecordRequest
import darabonba.core.client.ClientOverrideConfiguration

class AliyunDomainHelper(private val accessKeyId:String, private val accessKeySecret:String) {
  private fun createClient(): AsyncClient {
    val provider = StaticCredentialProvider.create(
      Credential.builder()
        .accessKeyId(accessKeyId)
        .accessKeySecret(accessKeySecret) //.securityToken("<your-token>") // use STS token
        .build()
    )
    val client = AsyncClient.builder()
      .region("undefined") // 产品服务区域 ID
      //.httpClient(httpClient) // 将配置好的 HttpClient 传入，不传则使用默认 HttpClient（Apache HttpClient）
      .credentialsProvider(provider) //.serviceConfiguration(Configuration.create()) // 产品服务级别配置，可不设
      // Client 级别配置重写，可设置 RegionId、Endpoint、Http 请求参数等
      .overrideConfiguration(
        ClientOverrideConfiguration.create()
          .setEndpointOverride("alidns.cn-hangzhou.aliyuncs.com") //.setReadTimeout(Duration.ofSeconds(30))
      )
      .build()
    return client
  }

  fun getRecord(subDomain:String): MutableList<DescribeSubDomainRecordsResponseBody.Record> {
    val aliClient = createClient()
    val aliRequest = DescribeSubDomainRecordsRequest.builder()
      .subDomain(subDomain)
      .build()
    val resp = aliClient.describeSubDomainRecords(aliRequest).get()
    return resp.body.domainRecords.record
  }

  fun updateRecord(recordId:String,rr:String,value:String){
    val aliClient = createClient()
    val aliRequest = UpdateDomainRecordRequest.builder()
      .recordId(recordId)
      .RR(rr)
      .type("A")
      .value(value)
      .build()
    aliClient.updateDomainRecord(aliRequest).get()
  }

}
